/**
 * Created by yunpeng on 2015/3/30.
 */

var Table = require('../utils/Table').Table;
var crypto  = require('crypto');
var jwt = require('jsonwebtoken');
var secret = require('../utils/secret');

var Users = function (phone, nickname, openid, name, idcard, idCardPath, password,
                      usertype, createtime, authstate,carrierauthstate, address, introduce, company,
                      licences, roadlicences, evaluationnum,attitude,care,corresponds,headerpath,contact,contactnum) {
        this.phone = phone;
        this.nickname = nickname;
        this.openid = openid;
        this.name = name;
        this.idcard = idcard;
        this.idCardPath = idCardPath;
        this.password = password;
        this.usertype = usertype;
        this.createtime = createtime;
        this.authstate = authstate;//认证状态
        this.carrierauthstate = carrierauthstate;
        this.address = address;
        this.introduce = introduce;
        this.company = company;
        this.licences = licences;
        this.roadlicences = roadlicences;
        //this.evaluationtotal = evaluationtotal;
        this.evaluationnum  = evaluationnum;
        this.attitude = attitude;
        this.care = care;
        this.corresponds = corresponds;
        this.headerpath = headerpath;
        this.contact = contact;
        this.contactnum = contactnum;
    /**
     * 添加用户
     */
    if (typeof this.saveUser != 'function') {
        Users.prototype.saveUser = function (callback) {
            this.password = crypto.createHash('md5').update(this.password).digest('hex').toUpperCase();
            new Table('users').insert(this, function (err, result) {
                if (err) {
                    callback(500);
                } else {
                    callback({msg:true});
                }
            });
        }
    }
    if (typeof this.saveOtherUser != 'function') {
        Users.prototype.saveOtherUser = function (callback) {
            new Table('users').insert(this, function (err, result) {
                if (err) {
                    callback(500);
                } else {
                    callback({msg:true});
                }
            });
        }
    }
    /**
     * 检查用户是否存在
     */
    if (typeof this.checkUser != 'function') {
        console.log('sssss');
        Users.prototype.checkUser = function (phone,callback) {
            new Table().executeSql("SELECT * FROM users WHERE phone=?", [phone], function(err, result){
                if(err){
                    callback(false);
                }else{
                    if(result.length>0){
                        callback('hasUser');
                    }else{
                        callback(true);
                    }

                }
            });
        }
    }
    if (typeof this.checkUser1 != 'function') {
        console.log('sssss');
        Users.prototype.checkUser1 = function (phone,callback) {
            new Table().executeSql("SELECT * FROM users WHERE phone=?", [phone], function(err, result){
                if(err){
                    callback(false);
                }else{
                    if(result.length>0){
                        callback(result);
                    }else{
                        callback(false);
                    }

                }
            });
        }
    }
    if(typeof this.saveOpenid !='function'){
        Users.prototype.saveOpenid = function(phone,type,doc, callback){
            var val={};
            if(type=='openid') {
                val = {openid: doc};
            }else if(type=='pwd'){
                pwd = crypto.createHash('md5').update(doc.pwd).digest('hex').toUpperCase();
                val = {password:pwd,openid:doc.openid}
            }
            new Table('users').updateColumn('phone', phone,val, function(err,result){
                if(err){
                    callback(false);
                }else{
                    callback(result);
                }
            });
        }
    }
    if (typeof this.checkUserOpenid != 'function') {
        Users.prototype.checkUserOpenid = function (openid,callback) {
            new Table().executeSql("SELECT * FROM users WHERE openid=?", [openid], function(err, result){
                if(err){
                    callback(false);
                }else{
                    if(result.length>0){
                        callback(result);
                    }else{
                        callback(false);
                    }

                }
            });
        }
    }
    if(typeof this.Audit!='function'){
        Users.prototype.Audit=function(id,type,authstate,callback){
            if(authstate=='authstate'){
                var doc={authstate:type};
            }else{
                var doc={carrierauthstate:type};
            }
            new Table('users').updateColumn("id",id,doc,function(err,data){
                if(err){
                    callback(false);
                }else{
                    callback(true);
                }
            });
        }
    }
    if(typeof this.resetPass !='function'){
        Users.prototype.resetPass = function(phone,password, callback){
            password = crypto.createHash('md5').update(password).digest('hex').toUpperCase();
            var val = {password:password}
            new Table('users').updateColumn('phone', phone,val, function(err,result){
                if(err){
                    callback(500);
                }else{
                    callback({msg:true});
                }
            });
        }
    }



    if (typeof this.findUser != 'function') {
        Users.prototype.findUser = function (phone,password,type,callback) {
            password = crypto.createHash('md5').update(password).digest('hex').toUpperCase();
            var sql;
            if(type==1){
                type=2;
            }
            if(isNaN(phone)){//非数字或者不可转为数字 为数字的话认为是手机号登录
                if(type!=3){
                    sql = 'select * from users where nickname = ? and password = ? and (usertype='+type+' or usertype=1)';
                }else{
                    sql = 'select * from users where nickname = ? and password = ? and usertype='+type;
                }

            }else{
                if(type!=3){
                    sql = 'select * from users where phone = ? and password = ? and (usertype='+type+' or usertype=1)';
                }else{
                    sql = 'select * from users where phone = ? and password = ? and usertype='+type;
                }

            }

            new Table().executeSql(sql, [phone,password], function(err, result){
                if (err||!result||result.length==0) {
                    return callback(401);
                }
                var token = jwt.sign({id:result[0].id,usertype:result[0].usertype,headerpath:result[0].headerpath}, secret.secretToken, { expiresInMinutes: 60*24*20 });//20天
                delete result[0].password;
                callback({token:token,user:result[0]}) ;
            });
        }
    }

    if(typeof this.getList !='function'){//商家列表
        Users.prototype.getList = function(params,page,callback){
            var columns = ' * ';
            var condition1 =' AND l.id != '+params[0];
            if(params[1]&&params[1]!='null'){//开始时间
                condition1+=" AND l.createtime>'"+params[1]+"'";
            }
            if(params[2]&&params[2]!='null'){//结束时间
                condition1+=" AND l.createtime<'"+params[2]+"'";
            }
            if(params[3]&&params[3]!='null'){//商家名称模糊查询
                condition1+=" AND l.phone LIKE '%"+params[3]+"%'";
            }
            if(params[4]&&params[4]!=0){//商家名称模糊查询
                condition1+=" AND l.usertype = "+params[4]+" ";
            }

            new Table(' users l ').queryPage(columns,condition1,page,function(err,result){
                //console.log(result);
                callback(result);
            });
        }
    }


    if (typeof this.getAuthState != 'function') {
        Users.prototype.getAuthState = function (id,type,callback) {
            var sql;
            if(type==1){
                sql = 'select authstate from users where id = ?';
            }else{
                sql = 'select carrierauthstate from users where id = ?';//承运认证状态
            }


            new Table().executeSql(sql, [id], function(err, result){
                if (err||!result||result.length==0) {
                    return callback(401);
                }
                callback(err,{state:result[0]}) ;
            });
        }
    }


}

module.exports.Users  = Users;